#include <stdio.h>
#include <string.h>

#include "MzSQL.h"




MzSQL::MzSQL(char* dbpath){
	int ret = sqlite3_open(dbpath, &this->db);
    if(ret)
    {
        printf(" > MzSQL: can not open database.\n");
    }
    else  // return 0 -> success
    {
        printf(" > MzSQL: open database success.\n");
    }
    
    // init
    this->pStmt = NULL;
    this->result = NULL;
    this->errmsg = NULL;
}

MzSQL::~MzSQL(){
	if (this->errmsg != NULL) sqlite3_free(this->errmsg);
	if (this->result != NULL) sqlite3_free_table(this->result);
	if (this->pStmt != NULL) sqlite3_finalize(this->pStmt);
	sqlite3_close(this->db);
	printf(" > MzSQL: close database success.\n");
}


void MzSQL::getLastError(){
	printf(" > MzSQL: error: %s\n", this->errmsg);
}


bool MzSQL::execSql(char* sql){
	if (sqlite3_exec(this->db, sql, 0, 0, &this->errmsg) != SQLITE_OK ) {
        return false;     // if false call getlasterror to read reason
    }
	return true;
}

bool MzSQL::prepareSql(char* sql){
	if (sqlite3_prepare_v2(this->db, sql, -1, &this->pStmt, 0) != SQLITE_OK) {
        printf(" > MzSQL: error %s\n", sqlite3_errmsg(this->db));
        sqlite3_close(this->db);
        return false;
    }
    return true;
}

void MzSQL::bindInt(char* name, int n){
	int idx = sqlite3_bind_parameter_index(this->pStmt, name);
	sqlite3_bind_int(this->pStmt, idx, n);
}

void MzSQL::bindText(char* name, char* text){
	int idx = sqlite3_bind_parameter_index(this->pStmt, name);
	sqlite3_bind_text(this->pStmt, idx, text, strlen(text), NULL);
}


int MzSQL::step(){
	return sqlite3_step(this->pStmt);
}

const unsigned char* MzSQL::columnText(int iCol){
	return sqlite3_column_text(this->pStmt, iCol);
}

int MzSQL::columnInt(int iCol){
	return sqlite3_column_int(this->pStmt, iCol);
}


